'use strict';

exports.index = async ctx => {
  const { query } = ctx.request;
  const loginService = ctx.app.weapp.LoginService.create(ctx.request, ctx.response);
  const checkedData = await loginService.check();
  const { openId } = checkedData.userInfo;
  console.log('participated openId', openId);
  const { userId } = await ctx.model.WechatAccount.findByPk(openId);
  console.log('exports.index = async ctx userId', userId);
  const user = await ctx.model.User.findByPk(userId);
  let pageSize = 10;
  if (query.pageSize) pageSize = Number(query.pageSize);
  const where = {};
  const status = 'published';
  const { nameLike, storeClassId, id, type, include, longitude, latitude } = query;
  if (nameLike) where.name = { [ctx.model.Op.like]: `%${nameLike}%` };
  if (storeClassId) where.storeClassId = storeClassId;
  if (status) where.status = status;
  if (id) where.id = id;
  const options = {
    limit: pageSize,
    offset: query.currentPage ? pageSize * (query.currentPage - 1) : 0,
    where,
  };
  if (include === 'distance' && longitude && latitude) {
    options.attributes = {
      include: [[
        ctx.model.literal(`ROUND(
      6378.138 * 2 * ASIN(
          SQRT(
              POW(
                  SIN(
                      (
                          ${latitude} * PI() / 180 - ${ctx.model.col('latitude').col} * PI() / 180
                      ) / 2
                  ),
                  2
              ) + COS(${latitude} * PI() / 180) * COS(${ctx.model.col('latitude').col} * PI() / 180) * POW(
                  SIN(
                      (
                          ${longitude} * PI() / 180 - ${ctx.model.col('longitude').col} * PI() / 180
                      ) / 2
                  ),
                  2
              )
          )
      ) * 1000
  )`),
        'distance',
      ]],
    };
    options.order = [[ ctx.model.literal(`ROUND(
  6378.138 * 2 * ASIN(
      SQRT(
          POW(
              SIN(
                  (
                      ${latitude} * PI() / 180 - ${ctx.model.col('latitude').col} * PI() / 180
                  ) / 2
              ),
              2
          ) + COS(${latitude} * PI() / 180) * COS(${ctx.model.col('latitude').col} * PI() / 180) * POW(
              SIN(
                  (
                      ${longitude} * PI() / 180 - ${ctx.model.col('longitude').col} * PI() / 180
                  ) / 2
              ),
              2
          )
      )
  ) * 1000
)`), 'ASC' ]];
  }
  if (type === 'followed') {
    options.include = [
      {
        as: 'users',
        model: ctx.model.User,
        where: { id: user.id },
      },
    ];
    console.log('model.Store.findAndCountAll options include', options);
  }
  console.log('model.Store.findAndCountAll options', options);
  const {
    count: total, rows: list,
  } = await ctx.model.Store.findAndCountAll(options);
  ctx.body = {
    list,
    pagination: {
      total,
      pageSize,
      current: parseInt(query.currentPage, 10) || 1,
    },
  };
};

exports.show = async ctx => {
  const options = {
    include: [
      {
        model: ctx.model.StoreImage,
      },
    ],
  };
  const store = await ctx.model.Store.findByPk(ctx.params.id, options);
  const loginService = ctx.app.weapp.LoginService.create(ctx.request, ctx.response);
  const checkedData = await loginService.check();
  const { openId } = checkedData.userInfo;
  const currentWechatUser = await ctx.model.WechatAccount.findByPk(openId);
  const currentUser = await ctx.model.User.findByPk(currentWechatUser.userId);
  const followed = await store.hasUser(currentUser);
  console.log('exports.show followed', followed);
  store.dataValues.followed = followed;
  console.log('exports.show followed store', store);
  if (store) {
    ctx.body = store;
  } else {
    ctx.status = 404;
  }
};
